/** 数据字典工具类 */
import { computed } from 'vue';

import { useDictStore } from '#/store/dict';
import dataModule from '#/utils/dict/static.data';

export * from './shared';

export interface DictDataVO {
  dictType: string;
  label: string;
  value: number | string;
  isDefault: boolean;
  colorType: string;
  cssClass: string;
}

const dictStore = useDictStore();

const dictData = computed(() => {
  return dictStore.dictMap;
});

/**
 * 获取 dictType 对应的数据字典数组
 *
 * @param dictType 数据类型
 * @returns {any | Array} 数据字典数组
 */
export interface DictDataType {
  dictType?: string;
  label: string;
  value: boolean | null | number | string;
  key?: any;
  colorType?: string;
  cssClass?: string;
  isDefault?: boolean;
}

export function getDictDatas(dictType: string) {
  return dictData.value[dictType] || [];
}

export function getDictOpts(dictType: string) {
  /**
   * 这里原来是转换类型 转换类型后反而显示不出来正确的Tag 实际类型转换交给下面的getDictOptions来处理
   *
   * bugfix: dictOption.push({ ...dict, value: parseInt(dict.value + '') }) 原来的这种写法是造成页面卡死的原因
   */
  return getDictDatas(dictType);
}

// 处理所有options，默认按value顺序返回
function handleDictOptions(options: DictDataType[]) {
  try {
    return options.sort((a, b) => a.value - b.value);
  } catch {
    return options;
  }
}

export async function getDictDatasAsync(
  dictTypeParams: { type: string; valueType?: string }[],
) {
  const dictDataMap: Record<string, DictDataType[]> = {};
  const foundTypes = new Set<string>();
  // 处理静态字典数据
  for (const dictType of Object.keys(dataModule)) {
    console.log(dataModule, dictType);

    const dictParam = dictTypeParams.find((d) => d.type === dictType);
    console.log(dictTypeParams, dictParam);

    if (dictParam) {
      const dictEntries = dataModule[dictType];
      if (dictEntries && dictEntries.data && dictEntries.data.length > 0) {
        dictEntries.data.forEach((dictData) => {
          dictData.type = dictType;

          if (!dictDataMap[dictType]) {
            dictDataMap[dictType] = [];
          }
          dictDataMap[dictType].push({
            ...dictData,
            value: convertValue(dictData.value, dictParam.valueType),
            label: dictData.label,
            colorType: dictData.colorType,
            cssClass: dictData.cssClass,
            extend1: dictData.extend1,
            extend2: dictData.extend2,
          } as DictDataType);
        });
        dictDataMap[dictType] = handleDictOptions(dictDataMap[dictType] || []);
        foundTypes.add(dictType);
      }
      // 如果所有类型都已找到，提前返回
      if (foundTypes.size === dictTypeParams.length) {
        return dictDataMap;
      }
    }
  }

  // 并行获取远程字典数据
  // const promises = dictTypeParams.map(async ({ type, valueType }) => {
  //   if (!foundTypes.has(type)) {
  //     try {
  //       const data = await Apis.dictData.get_page({
  //         params: { type },
  //       });
  //       dictDataMap[type] = (data.rows || []).map((dictData: any) => ({
  //         ...dictData,
  //         value: convertValue(dictData.value, valueType),
  //         label: dictData.name,
  //         colorType: dictData.colorType,
  //         cssClass: dictData.cssClass,
  //         extend1: dictData.extend1,
  //         extend2: dictData.extend2,
  //       }));
  //       dictDataMap[type] = handleDictOptions(dictDataMap[type] || []);
  //     } catch (error) {
  //       console.error(`Failed to fetch data for type ${type}:`, error);
  //     }
  //   }
  // });

  // await Promise.all(promises);
  return dictDataMap;
}

export function getDictOptions(
  dictType: string,
  valueType?: 'boolean' | 'number' | 'string',
): any[] {
  let dictOption: DictDataType[] = [];
  valueType ||= 'string';

  const dictOptions: DictDataType[] = dictData.value[dictType] || [];
  if (dictOptions && dictOptions.length > 0) {
    dictOptions.forEach((dict: DictDataType) => {
      dictOption.push({
        ...dict,
        key: dict.value,
        value: convertValue(dict.value, valueType),
      });
    });
  }

  try {
    // debugger;
    dictOption = dictOption.sort((a, b) => a.value - b.value);
  } catch {
    // console.error('Error sorting dictionary data:', error);
  }

  return dictOption;
}

function convertValue(value, type) {
  switch (type) {
    case 'boolean': {
      return value === 'true';
    }
    case 'number': {
      return Number.parseInt(value, 10);
    }
    case 'string': {
      return String(value);
    }
    default: {
      return value;
    }
  }
}
export async function getDictOptionsAsync(
  dictType: string,
  valueType: 'boolean' | 'number' | 'string' = 'string',
): Promise<DictDataType[]> {
  try {
    const response = await getDictDatasAsync([{ type: dictType, valueType }]);
    console.log(response);
    const dictOptions: DictDataType[] = response[dictType] || [];

    return dictOptions.map((dict: DictDataType) => ({
      ...dict,
      key: dict.value,
      value: convertValue(dict.value, valueType),
    }));
  } catch (error) {
    console.error('Error fetching dictionary data:', error);
    return [];
  }
}

/** 获取指定 value 的字典数据 */
export function getDictObj(dictType: string, value: any): DictDataType | null {
  const dictOptions: DictDataType[] = getDictDatas(dictType);
  if (dictOptions) {
    if (value) {
      return (
        dictOptions.find(
          (dict: DictDataType) => dict.value === value.toString(),
        ) || null
      );
    }
    return null;
  } else {
    return null;
  }
}

/** 获取指定 value 的字典数据 */
export function getDictObjByOptions(
  options: DictDataType[],
  value: any,
): DictDataType | null {
  if (options) {
    if (value !== undefined) {
      const result = options.find((dict: DictDataType) => dict.value == value);
      return result || null;
    }
    return null;
  } else {
    return null;
  }
}

/** 获取指定 value 的字典数据 */
export async function getDictObjAsync(
  dictType: string,
  value: any,
): Promise<DictDataType | null> {
  const dictOptions = await getDictOptionsAsync(dictType);
  if (dictOptions) {
    if (value) {
      return (
        dictOptions.find(
          (dict: DictDataType) => dict.value === value.toString(),
        ) || null
      );
    }
    return null;
  } else {
    return null;
  }
}

/** 获取字典默认数据 */
export function getDictDefaultObj(dictType: string): DictDataType | null {
  const dictOptions: DictDataType[] = getDictDatas(dictType);
  return dictOptions
    ? dictOptions.find((dict: DictDataType) => dict.isDefault == '1') ||
        dictOptions[0]
    : null;
}

/**
 * 字典工具类
 */
export const dictUtils = {
  /** 异步获取字典数据 */
  getDictDatasAsync,

  /** 获取字典数据 */
  getDictOptions,

  /** 异步获取字典数据 */
  getDictOptionsAsync,

  /** 获取指定 value 的字典数据 */
  getDictObjAsync,

  /** 通过字典数据获取默认某个字典数据 */
  getDictDefaultObjByOptions: (options: DictDataVO[]): DictDataVO | null => {
    return options
      ? options.find((dict: DictDataVO) => dict.isDefault) || options[0] || null
      : null;
  },

  /** 通过字典类型获取字典默认数据 */
  getDictDefaultObj: (dictType: string): DictDataVO | null => {
    const dictOptions: DictDataVO[] = getDictDatas(dictType);
    return dictOptions
      ? dictOptions.find((dict: DictDataVO) => dict.isDefault) ||
          dictOptions[0] ||
          null
      : null;
  },
};
